package cn.crc.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class EasyUDPServer {
    public static void main(String[] args)throws IOException {
        String messg = "这里是肯德基，您的芝士汉堡已经制作完毕，祝您用餐愉快";//要发送的信息
        DatagramSocket socket = new DatagramSocket(9999);//建立socket
        try {
            byte[] sendData;//建立收发容器
            byte[] receiveData = new byte[1024];

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);//接收数据包
            socket.receive(receivePacket);
            String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Received from client:" + receivedMessage);

            sendData = messg.getBytes();//发送数据包
            InetAddress clientAddress = receivePacket.getAddress();
            int clientPort = receivePacket.getPort();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
            socket.send(sendPacket);
        }finally {
            if(socket != null && !socket.isClosed()) socket.close();///关闭套接字
        }
    }
}
